package com.micangcaihang.micang.mvp.task.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.micangcaihang.common.base.fragment.BaseFragment;
import com.micangcaihang.common.utils.Properties;
import com.micangcaihang.common.utils.StringUtils;
import com.micangcaihang.common.utils.TimeUtils;
import com.micangcaihang.common.utils.ToastUtils;
import com.micangcaihang.micang.R;
import com.micangcaihang.micang.databinding.FragmentTaskBorrowerInfoFBinding;
import com.micangcaihang.micang.entity.EventCenter;
import com.micangcaihang.micang.entity.FTaskBorrowerInfoEntity;
import com.micangcaihang.micang.entity.MatesRequest;
import com.micangcaihang.micang.entity.PickerEntity;
import com.micangcaihang.micang.entity.ProvinceEntity;
import com.micangcaihang.micang.http.request.FTaskBorrowerInfoRequest;
import com.micangcaihang.micang.mvp.task.contract.FTaskBorrowerInfoContract;
import com.micangcaihang.micang.mvp.task.presenter.FTaskBorrowerInfoPresenter;
import com.micangcaihang.micang.view.PickerViewHelper;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * <pre>
 *     author : Fandy
 *     e-mail : fandayongfly@gmail.com
 *     time   : 2017/07/24
 *     update : 2017/07/24
 *     desc   : 风控 借款人信息
 *     version: 1.0
 * </pre>
 */

public class FTaskBorrowerInfoFragment extends BaseFragment<FTaskBorrowerInfoPresenter,
        FragmentTaskBorrowerInfoFBinding> implements FTaskBorrowerInfoContract.View {
    private String id;
    private FTaskBorrowerInfoRequest mRequest;
    private FTaskBorrowerInfoRequest mOldRequest;
    private int pickerType;
    private boolean isNetSuccess;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = getArguments().getString("id");
    }

    public static FTaskBorrowerInfoFragment newInstance(String id) {
        Bundle args = new Bundle();
        FTaskBorrowerInfoFragment fragment = new FTaskBorrowerInfoFragment();
        args.putString("id", id);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 获取资源文件布局
     *
     * @return 资源布局文件layout
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_task_borrower_info_f;
    }

    @Override
    protected void initData() {
        super.initData();
        mRequest = new FTaskBorrowerInfoRequest();
        mRequest.setId(id);
        mOldRequest = new FTaskBorrowerInfoRequest();
        mOldRequest.setId(id);
    }

    @Override
    public void initPresenter() {
        super.initPresenter();
        mPresenter.setId(id);
    }

    /**
     * 初始化按钮监听
     */
    @Override
    protected void initListener() {
        mViewBinding.setClickHandler(new FTaskBorrowerInfoFragment.ClickHandler());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mViewBinding.matesLayout.destroy();
    }

    /**
     * 返回下拉框信息
     *
     * @param list
     * @param type
     */
    @Override
    public void returnPickerViewData(List<PickerEntity> list, String type) {
        switch (pickerType) {
            case 1:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getCustomer_sex(), list,
                        pickerEntity1 -> {
                            mRequest.setCustomer_sex(pickerEntity1.getSign_id());
                            mViewBinding.tvCustomerSex.setText(pickerEntity1.getTitle());
                        });
                break;
            case 2:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getCertificate_type(), list,
                        pickerEntity1 -> {
                            mRequest.setCertificate_type(pickerEntity1.getSign_id());
                            mViewBinding.tvCertificateType.setText(pickerEntity1.getTitle());
                        });
                break;
            case 3:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getMarriage_status(), list,
                        pickerEntity1 -> {
                            mRequest.setMarriage_status(pickerEntity1.getSign_id());
                            mViewBinding.tvMarriageStatus.setText(pickerEntity1.getTitle());
                            if ("1".equals(mRequest.getMarriage_status())) {
                                mViewBinding.matesLayout.setType(1);
                                EventBus.getDefault().post(new EventCenter(EventCenter.TASK_MARRIAGE_STATUS1));
                            } else if ("2".equals(mRequest.getMarriage_status())) {
                                mViewBinding.matesLayout.setType(2);
                                EventBus.getDefault().post(new EventCenter(EventCenter.TASK_MARRIAGE_STATUS2));
                            } else if ("3".equals(mRequest.getMarriage_status())) {
                                mViewBinding.matesLayout.setType(3);
                                EventBus.getDefault().post(new EventCenter(EventCenter.TASK_MARRIAGE_STATUS3));
                            } else if ("4".equals(mRequest.getMarriage_status())) {
                                mViewBinding.matesLayout.setType(4);
                                EventBus.getDefault().post(new EventCenter(EventCenter.TASK_MARRIAGE_STATUS4));
                            } else if ("5".equals(mRequest.getMarriage_status())) {
                                mViewBinding.matesLayout.setType(5);
                                EventBus.getDefault().post(new EventCenter(EventCenter.TASK_MARRIAGE_STATUS5));
                            } else {
                                mViewBinding.matesLayout.setType(0);
                            }
                        });
                break;
            case 4:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getCustomer_nationality(), list,
                        pickerEntity1 -> {
                            mRequest.setCustomer_nationality(pickerEntity1.getSign_id());
                            mViewBinding.tvCustomerNationality.setText(pickerEntity1.getTitle());
                        });
                break;
            case 5:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getPeason_credit(), list,
                        pickerEntity1 -> {
                            mRequest.setPeason_credit(pickerEntity1.getSign_id());
                            mViewBinding.tvPeasonCredit.setText(pickerEntity1.getTitle());
                        });
                break;
            case 6:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getPeason_crediless(), list,
                        pickerEntity1 -> {
                            mRequest.setPeason_crediless(pickerEntity1.getSign_id());
                            mViewBinding.tvPeasonCrediless.setText(pickerEntity1.getTitle());
                        });
                break;
            case 7:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getPeason_enforced(), list,
                        pickerEntity1 -> {
                            mRequest.setPeason_enforced(pickerEntity1.getSign_id());
                            mViewBinding.tvPeasonEnforced.setText(pickerEntity1.getTitle());
                        });
                break;
            case 8:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getAsset_survey(), list,
                        pickerEntity1 -> {
                            mRequest.setAsset_survey(pickerEntity1.getSign_id());
                            mViewBinding.tvAssetSurvey.setText(pickerEntity1.getTitle());
                        });
                break;
            case 9:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getVocation_type(), list,
                        pickerEntity1 -> {
                            mRequest.setVocation_type(pickerEntity1.getSign_id());
                            mViewBinding.tvVocationType.setText(pickerEntity1.getTitle());
                        });
                break;
            case 10:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getOccupation_type(), list,
                        pickerEntity1 -> {
                            mRequest.setOccupation_type(pickerEntity1.getSign_id());
                            mViewBinding.tvOccupationType.setText(pickerEntity1.getTitle());
                        });
                break;
        }
    }

    /**
     * 返回借款人信息
     *
     * @param entity
     */
    @Override
    public void returnBorrowerInfoData(FTaskBorrowerInfoEntity entity) {
        isNetSuccess = true;
        String[] excludsArray = new String[]{"choose_list", "id", "mates"};
        try {
            Properties.copyPropertiesExclude(entity, mRequest, excludsArray);
            Properties.copyPropertiesExclude(entity, mOldRequest, excludsArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ////借款人姓名
        if (!StringUtils.isEmpty(entity.getCustomer_name())) {
            mViewBinding.etCustomerName.setText(entity.getCustomer_name());
        }
        //证件号码
        if (!StringUtils.isEmpty(entity.getCertificate_number())) {
            mViewBinding.etCertificateNumber.setText(entity.getCertificate_number());
        }
        //生日
        if (!StringUtils.isEmpty(entity.getCustomer_birthday())) {
            String birthday = TimeUtils.millis2StringDay(Long.parseLong(entity.getCustomer_birthday()) * 1000);
            mViewBinding.tvCustomerBirthday.setText(birthday);
        }
        //户口所在地
        if (!StringUtils.isEmpty(entity.getMobile_phone())) {
            mViewBinding.etMobilePhone.setText(entity.getMobile_phone());
        }
        //户口所在地
        if (!StringUtils.isEmpty(entity.getId_residence())) {
            mViewBinding.etIdResidence.setText(entity.getId_residence());
        }
        //个人月收入
        if (!StringUtils.isEmpty(entity.getMonth_income())) {
            mViewBinding.etMonthIncome.setText(entity.getMonth_income());
        }
        //个人年收入
        if (!StringUtils.isEmpty(entity.getCustomer_income())) {
            mViewBinding.etCustomerIncome.setText(entity.getCustomer_income());
        }
        //家庭年收入
        if (!StringUtils.isEmpty(entity.getHome_income())) {
            mViewBinding.etHomeIncome.setText(entity.getHome_income());
        }
        //////联系地址
        if (!StringUtils.isEmpty(entity.getContact_address())) {
            mViewBinding.etContactAddress.setText(entity.getContact_address());
        }
        ////客户来源
        if (!StringUtils.isEmpty(entity.getCustomer_source())) {
            mViewBinding.etCustomerSource.setText(entity.getCustomer_source());
        }
        //查询时间
        if (!StringUtils.isEmpty(entity.getQuery_time())) {
            String queryTime = TimeUtils.millis2StringDay(Long.parseLong(entity.getQuery_time()) * 1000);
            mViewBinding.tvQueryTime.setText(queryTime);
        }

        if ("1".equals(entity.getMarriage_status())) {
            mViewBinding.matesLayout.setType(1);
        } else if ("2".equals(entity.getMarriage_status())) {
            mViewBinding.matesLayout.setType(2);
        } else if ("3".equals(entity.getMarriage_status())) {
            mViewBinding.matesLayout.setType(3);
        } else if ("4".equals(entity.getMarriage_status())) {
            mViewBinding.matesLayout.setType(4);
        } else if ("5".equals(entity.getMarriage_status())) {
            mViewBinding.matesLayout.setType(5);
        } else {
            mViewBinding.matesLayout.setType(0);
        }
        if (entity.getMates() != null) {
            mViewBinding.matesLayout.setMatesEntities(entity.getMates());
            mOldRequest.setMates(mViewBinding.matesLayout.getMatesRequests());
        }
        if (entity.getChoose_list() != null) {
            FTaskBorrowerInfoEntity.ChooseListBean choose_list = entity.getChoose_list();
            //性别
            if (!StringUtils.isEmpty(choose_list.getCustomer_sex())) {
                mViewBinding.tvCustomerSex.setText(choose_list.getCustomer_sex());
            }
            ////证件类型
            if (!StringUtils.isEmpty(choose_list.getCertificate_type())) {
                mViewBinding.tvCertificateType.setText(choose_list.getCertificate_type());
            }
            //婚姻
            if (!StringUtils.isEmpty(choose_list.getMarriage_status())) {
                mViewBinding.tvMarriageStatus.setText(choose_list.getMarriage_status());
            }
            //国籍
            if (!StringUtils.isEmpty(choose_list.getCustomer_nationality())) {
                mViewBinding.tvCustomerNationality.setText(choose_list.getCustomer_nationality());
            }
            //省市县
            StringBuffer province = new StringBuffer();
            if (!StringUtils.isEmpty(choose_list.getResident_province())) {
                province.append(choose_list.getResident_province());
            }
            if (!StringUtils.isEmpty(choose_list.getResident_city())) {
                province.append(choose_list.getResident_city());
            }
            if (!StringUtils.isEmpty(choose_list.getResident_county())) {
                province.append(choose_list.getResident_county());
            }
            mViewBinding.tvResidentProvince.setText(province.toString());
            // //征信状况
            if (!StringUtils.isEmpty(choose_list.getPeason_credit())) {
                mViewBinding.tvPeasonCredit.setText(choose_list.getPeason_credit());
            }
            //是否失信
            if (!StringUtils.isEmpty(choose_list.getPeason_crediless())) {
                mViewBinding.tvPeasonCrediless.setText(choose_list.getPeason_crediless());
            }
            //是否被执行
            if (!StringUtils.isEmpty(choose_list.getPeason_enforced())) {
                mViewBinding.tvPeasonEnforced.setText(choose_list.getPeason_enforced());
            }
            //资产调查
            if (!StringUtils.isEmpty(choose_list.getAsset_survey())) {
                mViewBinding.tvAssetSurvey.setText(choose_list.getAsset_survey());
            }
            //行业类别
            if (!StringUtils.isEmpty(choose_list.getVocation_type())) {
                mViewBinding.tvVocationType.setText(choose_list.getVocation_type());
            }
            //职业类别
            if (!StringUtils.isEmpty(choose_list.getOccupation_type())) {
                mViewBinding.tvOccupationType.setText(choose_list.getOccupation_type());
            }
        }
    }

    /**
     * 返回省市县信息
     *
     * @param provinceEntities
     */
    @Override
    public void returnProvinceData(List<ProvinceEntity> provinceEntities) {
        PickerViewHelper.showProvinceThree(_mActivity, "客户地区", provinceEntities,
                mRequest.getResident_province(), mRequest.getResident_city(), mRequest.getResident_county(),
                (provinceEntity, cityBean, areaBean) -> {
                    mRequest.setResident_province(provinceEntity.getCode());
                    mRequest.setResident_city(cityBean.getCode());
                    mRequest.setResident_county(areaBean.getCode());
                    //省市县
                    StringBuffer province = new StringBuffer();
                    if (!StringUtils.isEmpty(provinceEntity.getName())) {
                        province.append(provinceEntity.getName());
                    }
                    if (!StringUtils.isEmpty(cityBean.getName())) {
                        province.append(cityBean.getName());
                    }
                    if (!StringUtils.isEmpty(areaBean.getName())) {
                        province.append(areaBean.getName());
                    }
                    mViewBinding.tvResidentProvince.setText(province.toString());
                });
    }


    public class ClickHandler {
        //性别
        public void onShowCustomerSexPickerView(View view) {
            pickerType = 1;
            mPresenter.loadPickerViewData("sex_list", "性别");
        }

        //证件类型
        public void onShowCertificateTypePickerView(View view) {
            pickerType = 2;
            mPresenter.loadPickerViewData("certificate_type", "证件类型");
        }

        //婚姻
        public void onShowMarriageStatusPickerView(View view) {
            pickerType = 3;
            mPresenter.loadPickerViewData("marriage_status", "婚姻");
        }

        //生日
        public void onShowCustomerBirthdayPickerView(View view) {
            Calendar startDate = Calendar.getInstance();
            startDate.set(1952, 0, 1);
            Calendar endData = Calendar.getInstance();//系统当前时间
            Calendar selectData = Calendar.getInstance();
            if (!StringUtils.isEmpty(mRequest.getCustomer_birthday())) {
                selectData.setTime(TimeUtils.millis2Date(Long.parseLong(mRequest.getCustomer_birthday()) * 1000));
            }
            PickerViewHelper.showYearMonthDayPicker(_mActivity, "客户生日", startDate, endData, selectData, new PickerViewHelper.OnTimeSelectListenner() {
                @Override
                public void onTimeSelect(Date date) {
                    String date2String = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()));
                    mViewBinding.tvCustomerBirthday.setText(date2String);
                    String checkin_date = String.valueOf(TimeUtils.string2Millis(date2String, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())) / 1000);
                    mRequest.setCustomer_birthday(checkin_date);
                }
            });
        }

        //国籍
        public void onShowCustomerNationalityPickerView(View view) {
            pickerType = 4;
            mPresenter.loadPickerViewData("country_code", "国籍");
        }

        public void onShowResidentProvincePickerView(View view) {
            mPresenter.loadProvinceDataData();
        }

        //征信状况
        public void onShowPeasonCreditPickerView(View view) {
            pickerType = 5;
            mPresenter.loadPickerViewData("peason_credit", "征信状况");
        }

        public void onShowPeasonCredilessPickerView(View view) {
            pickerType = 6;
            mPresenter.loadPickerViewData("li_boolean", "是否失信");
        }

        public void onShowPeasonEnforcedPickerView(View view) {
            pickerType = 7;
            mPresenter.loadPickerViewData("li_boolean", "是否被执行");
        }

        //查询时间
        public void onShowQueryTimePickerView(View view) {
            Calendar startDate = Calendar.getInstance();
            startDate.set(1955, 0, 1);
            Calendar endData = Calendar.getInstance();//系统当前时间
            Calendar selectData = Calendar.getInstance();
            if (!StringUtils.isEmpty(mRequest.getQuery_time())) {
                selectData.setTime(TimeUtils.millis2Date(Long.parseLong(mRequest.getQuery_time()) * 1000));
            }
            PickerViewHelper.showYearMonthDayPicker(_mActivity, "查询时间(征信)", startDate, endData, selectData, new PickerViewHelper.OnTimeSelectListenner() {
                @Override
                public void onTimeSelect(Date date) {
                    String date2String = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()));
                    mViewBinding.tvQueryTime.setText(date2String);
                    String checkin_date = String.valueOf(TimeUtils.string2Millis(date2String, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())) / 1000);
                    mRequest.setQuery_time(checkin_date);
                }
            });
        }

        public void onShowAssetSurveyPickerView(View view) {
            pickerType = 8;
            mPresenter.loadPickerViewData("is_have", "资产调查");
        }

        public void onShowVocationTypePickerView(View view) {
            pickerType = 9;
            mPresenter.loadPickerViewData("industry_type", "行业类别");
        }

        public void onShowOccupationTypePickerView(View view) {
            pickerType = 10;
            mPresenter.loadPickerViewData("occupation", "职业类别");
        }

        public void onSave(View view) {
            saveData();
        }
    }

    public void saveData() {
        setSaveData();
        if (mRequest.toString().equals(mOldRequest.toString())) {
            ToastUtils.showLong("您没有更改任何信息，无需保存");
            return;
        }
        isNetSuccess = false;
        mPresenter.saveBorrowerInfo(mRequest);
    }

    /**
     * 判断是否保存过数据 没有的话点击保存去保存
     *
     * @return 是否保存当前页面数据
     */
    public boolean isSaveData() {
        //如果请求错误则返回true
        if (!isNetSuccess) {
            return true;
        }
        setSaveData();
        if (mRequest.toString().equals(mOldRequest.toString())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * s设置请求数据
     */
    private void setSaveData() {
        mRequest.setCustomer_name(mViewBinding.etCustomerName.getText().toString().trim());
        mRequest.setCertificate_number(mViewBinding.etCertificateNumber.getText().toString().trim());
        mRequest.setId_residence(mViewBinding.etIdResidence.getText().toString().trim());
        mRequest.setMonth_income(mViewBinding.etMonthIncome.getText().toString().trim());
        mRequest.setCustomer_income(mViewBinding.etCustomerIncome.getText().toString().trim());
        mRequest.setHome_income(mViewBinding.etHomeIncome.getText().toString().trim());
        mRequest.setMobile_phone(mViewBinding.etMobilePhone.getText().toString().trim());
        mRequest.setContact_address(mViewBinding.etContactAddress.getText().toString().trim());
        mRequest.setCustomer_source(mViewBinding.etCustomerSource.getText().toString().trim());
        List<MatesRequest> matesRequests = mViewBinding.matesLayout.getMatesRequests();
        mRequest.setMates(matesRequests);
    }
}
